package com.cloudinnov.logic.impl;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudinnov.dao.AlarmRuleDao;
import com.cloudinnov.dao.AlarmRulePointDao;
import com.cloudinnov.dao.FaultsDao;
import com.cloudinnov.logic.AlarmRuleLogic;
import com.cloudinnov.model.AlarmRule;
import com.cloudinnov.model.AlarmRulePoint;
import com.cloudinnov.model.Faults;
import com.cloudinnov.utils.CodeUtil;
import com.cloudinnov.utils.CommonUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.exceptions.JedisException;

@Service
public class AlarmRuleLogicImpl extends BaseLogicImpl<AlarmRule> implements AlarmRuleLogic {
	private static final Logger LOG = LoggerFactory.getLogger(AlarmRuleLogicImpl.class);
	private static final String ALARMRULE_REDIS_KEY = "alarmRule:";
	private static final String ALARMRULE_REDIS_NAME = ":name";
	private static final String ALARMRULE_REDIS_CONFIG = "config";
	private static final String ALARMRULE_CODE_REDIS_KEY = "alarmRuleCode";
	@Autowired
	private AlarmRuleDao alarmRuleDao;
	@Autowired
	private AlarmRulePointDao alarmRulePointDao;
	@Autowired
	private FaultsDao faultsDao;
	@Autowired
	private JedisPool jedisPool;

	@Override
	public int save(AlarmRule alarmRule) {
		Jedis alarmRuleRedis = null;
		int result = 0;
		try {
			alarmRuleRedis = jedisPool.getResource();
			alarmRule.setCode(CodeUtil.alarmRuleCode(5));// 获取告警规则code
			result = alarmRuleDao.insert(alarmRule);
			Faults fault = new Faults();
			fault.setCode(alarmRule.getFaultCode());
			fault.setLanguage(alarmRule.getLanguage());
			fault = faultsDao.selectEntityByCondition(fault);
			if (fault != null) {
				alarmRule.setFaultCode(fault.getFaultCode());
			}
			alarmRuleRedis.hset(ALARMRULE_REDIS_KEY + alarmRule.getCode() + ALARMRULE_REDIS_NAME,
					ALARMRULE_REDIS_CONFIG, JSON.toJSONString(alarmRule));// 把告警规则基础配置信息存入故障redis数据库
			if (result == CommonUtils.SUCCESS_NUM) {
				AlarmRulePoint alarmRulePoint = null;
				// 对condition（json格式）处理
				if (alarmRule.getCondition() == null || alarmRule.getCondition().length() == 0) {
					result = 0;
				}
				List<String> conditions = JSON.parseArray(alarmRule.getCondition(), String.class);
				for (int i = 0; i < conditions.size(); i++) {
					alarmRulePoint = new AlarmRulePoint();
					alarmRulePoint.setCode(alarmRule.getCode());
					alarmRulePoint.setComment(alarmRule.getComment());
					alarmRulePoint.setCode(alarmRule.getCode());
					alarmRulePoint.setComment(alarmRule.getComment());
					JSONObject con = JSON.parseObject(conditions.get(i));
					alarmRulePoint.setPointCode(con.getString("code"));
					alarmRulePoint.setName(con.getString("name"));
					List<String> rulesAddList = JSON
							.parseArray(JSON.parseArray(con.getString("rulesAddList")).toJSONString(), String.class);
					String conddition = "";
					for (int j = 0; j < rulesAddList.size(); j++) {
						JSONObject rule = JSON.parseObject(rulesAddList.get(j));
						conddition += rule.getString("are") + "," + rule.getString("omg") + "|";
					}
					alarmRulePoint.setCondition(conddition);
					alarmRulePointDao.insert(alarmRulePoint);
				}
			}
		} catch (JedisException e) {
			LOG.error("alarmRule Save JedisException:", e);
		} finally {
			jedisPool.returnResource(alarmRuleRedis);
		}
		return result;
	}
	@Override
	public int update(AlarmRule alarmRule) {
		Jedis alarmRuleRedis = null;
		int result = 0;
		try {
			alarmRuleRedis = jedisPool.getResource();
			AlarmRulePoint alarmRulePoint = new AlarmRulePoint();
			alarmRulePoint.setCode(alarmRule.getCode());
			alarmRulePoint.setComment(alarmRule.getComment());
			result = alarmRuleDao.updateByCondition(alarmRule);
			if (result == CommonUtils.SUCCESS_NUM) {
				// 删除告警规则点位配置
				result = alarmRulePointDao.deleteByCondition(alarmRulePoint);
				alarmRuleRedis.del(ALARMRULE_REDIS_KEY + alarmRule.getCode() + ALARMRULE_REDIS_NAME);// 先删除redis配置信息
				Faults fault = new Faults();
				fault.setCode(alarmRule.getFaultCode());
				fault.setLanguage(alarmRule.getLanguage());
				fault = faultsDao.selectEntityByCondition(fault);
				if (fault != null) {
					alarmRule.setFaultCode(fault.getFaultCode());
				}
				alarmRuleRedis.hset(ALARMRULE_REDIS_KEY + alarmRule.getCode() + ALARMRULE_REDIS_NAME,
						ALARMRULE_REDIS_CONFIG, JSON.toJSONString(alarmRule));// 把告警规则基础配置信息存入故障redis数据库
				// 对condition（json格式）处理
				if (alarmRule.getCondition() == null || alarmRule.getCondition().length() == 0) {
					result = 0;
				}
				List<String> conditions = JSON.parseArray(alarmRule.getCondition(), String.class);
				for (int i = 0; i < conditions.size(); i++) {
					alarmRulePoint.setCode(alarmRule.getCode());
					alarmRulePoint.setComment(alarmRule.getComment());
					JSONObject con = JSON.parseObject(conditions.get(i));
					alarmRulePoint.setPointCode(con.getString("code"));
					alarmRulePoint.setName(con.getString("name"));
					List<String> rulesAddList = JSON
							.parseArray(JSON.parseArray(con.getString("rulesAddList")).toJSONString(), String.class);
					String conddition = "";
					for (int j = 0; j < rulesAddList.size(); j++) {
						JSONObject rule = JSON.parseObject(rulesAddList.get(j));
						conddition += rule.getString("are") + "," + rule.getString("omg") + "|";
					}
					alarmRulePoint.setCondition(conddition);
					alarmRulePointDao.insert(alarmRulePoint);
				}
			}
		} catch (JedisException e) {
			LOG.error("alarmRule Save JedisException:", e);
		} finally {
			jedisPool.returnResource(alarmRuleRedis);
		}
		return result;
	}
	@Override
	public int delete(AlarmRule alarmRule) {
		Jedis alarmRuleRedis = null;
		int result = 0;
		try {
			alarmRuleRedis = jedisPool.getResource();
			AlarmRulePoint alarmRulePoint = new AlarmRulePoint();
			alarmRulePoint.setCode(alarmRule.getCode());
			result = alarmRuleDao.deleteByCondition(alarmRule);
			if (result == CommonUtils.SUCCESS_NUM) {
				// 删除告警规则点位配置
				alarmRulePointDao.deleteByCondition(alarmRulePoint);
				alarmRuleRedis.del(ALARMRULE_REDIS_KEY + alarmRule.getCode() + ALARMRULE_REDIS_NAME);// 删除redis配置信息
				alarmRuleRedis.srem(ALARMRULE_CODE_REDIS_KEY, alarmRule.getCode());// 删除告警规则编码Set集合中的告警规则编码
			}
		} catch (JedisException e) {
			LOG.error("alarmRule Save JedisException:", e);
		} finally {
			jedisPool.returnResource(alarmRuleRedis);
		}
		return result;
	}
	@Override
	public int updateAlarmRuleOnOff(String code, Integer onOff) {
		return alarmRuleDao.updateAlarmRuleOnOff(code, onOff);
	}
}
